package com.studentms.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 对所有数据进行乱码处理
 */
public class EncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器开始");
        //处理乱码
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        request.setCharacterEncoding("utf-8");

        //防止用户在未登录的情况下访问资源
        String requestURI = request.getRequestURI();
        System.out.println("requestURL"+requestURI);
        Object u1 = request.getSession().getAttribute("u1");
        System.out.println(u1);
        if (requestURI.endsWith("index.jsp")&&u1==null){
            response.sendRedirect("login.jsp");
        }
        if (requestURI.endsWith("head.jsp")&&u1==null){
            response.sendRedirect("login.jsp");
        }
        if (requestURI.endsWith("left.jsp")&&u1==null){
            response.sendRedirect("login.jsp");
        }
        if (requestURI.endsWith("right.jsp")&&u1==null){
            response.sendRedirect("login.jsp");
        }
        if (requestURI.endsWith("if.jsp")&&u1==null){
            response.sendRedirect("login.jsp");
        }
        //调取下一个过滤器，或者调取servlet
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("过滤器结束");
    }

    @Override
    public void destroy() {

    }
}
